package com.cxs.controller;

import com.cxs.config.CommonConfig;
import com.cxs.dto.UserDTO;
import com.cxs.utils.DataUtil;
import com.cxs.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Project: postman-demo
 * @Author: cxs2014501@163.com
 * @Create: 2022/11/8 13:48
 * @Description:
 **/
@RestController
@RequestMapping("/postman")
public class PostmanController {

    @Autowired
    private CommonConfig commonConfig;

    @GetMapping("/getUserList")
    public R getUserList(){
        R r = R.resOk(commonConfig.getEnvName(), commonConfig.getPort());
        r.setData(DataUtil.getUserList());
        return r;
    }

    @DeleteMapping("/deleteById/{id}")
    public R deleteById(@PathVariable("id") String id){
        R r = R.resOk(commonConfig.getEnvName(), commonConfig.getPort());
        if (!StringUtils.hasLength(id)) {
            r.setCode(HttpStatus.BAD_REQUEST.value());
            r.setMsg("id岂能为空");
            return r;
        }
        Integer integer = DataUtil.removeUserById(id);
        if (integer == 1) {
            r.setMsg("删除成功");
        } else {
            r.setMsg("该用户不存在");
            r.setCode(201);
        }
        return r;
    }

    @PostMapping("/saveUser")
    public R saveUser(@RequestBody @Validated UserDTO user, BindingResult result){
        R r = R.resOk(commonConfig.getEnvName(), commonConfig.getPort());
        if (result.hasFieldErrors()) {
            r.setCode(HttpStatus.BAD_REQUEST.value());
            r.setMsg(result.getFieldError().getDefaultMessage());
            return r;
        }
        if (ObjectUtils.isEmpty(user)) {
            r.setCode(HttpStatus.BAD_REQUEST.value());
            r.setMsg("入参错误");
            return r;
        }
        Integer integer = DataUtil.saveUser(user);
        if (integer == 1) {
            r.setMsg("用户保存成功");
        } else {
            r.setMsg("用户保存失败,id重复了...");
            r.setCode(201);
        }
        return r;
    }
}
